<template>
  <div class="register-form px-6 py-8">
    <p class="text-base font-bold text-center pb-3">注册账号</p>
    <el-form :model="registerForm" :rules="registerFormRules" ref="formRef">
      <el-form-item prop="email">
        <el-input v-model="registerForm.email" placeholder="邮箱地址" size="large"></el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="registerForm.name" placeholder="昵称" size="large"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          placeholder="密码"
          size="large"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          placeholder="确认密码"
          size="large"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="text-right text-sm">
      <span class="register-btn cursor-pointer" @click="toLogin">已经有账号，去登录</span>
    </div>
    <div class="mt-3">
      <el-button class="w-full" type="primary" @click="registerAccount" :loading="loading"
        >注册</el-button
      >
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  FormRules,
  FormInstance,
  ElMessage,
} from 'element-plus'
import { trim } from 'lodash'
import { useRouter } from 'vue-router'
import { createUser } from '@/services/ApiServer/signInRequest'

export default defineComponent({
  name: 'registerForm',
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
  },
  setup() {
    let loading = ref(false)
    const registerForm = reactive({
      email: '',
      password: '',
      name: '',
      confirmPassword: '',
    })
    // email校验规则
    const validateEmail = (
      rule: any,
      value: string,
      callback: (error?: string | Error | undefined) => void
    ) => {
      if (trim(value) === '') {
        callback(new Error('请填写邮箱账号'))
      } else if (
        !/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value)
      ) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }
    // 密码校验规则
    const validPassword = (
      rule: any,
      value: string,
      callback: (error?: string | Error | undefined) => void
    ) => {
      if (trim(value) === '') {
        callback(new Error('请填写密码'))
      } else if (!/^[a-zA-Z0-9.~!@&%#_-]{6,16}$/.test(value)) {
        callback(new Error('密码为6至16位,可以包含“.~!@&%#_-”特殊字符'))
      } else {
        callback()
      }
    }
    // 确认密码校验规则
    const validConfirmPwd = (
      rule: any,
      value: string,
      callback: (error?: string | Error | undefined) => void
    ) => {
      if (trim(value) === '') {
        callback(new Error('请填写确认密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('确认密码不相同'))
      } else {
        callback()
      }
    }
    const transformValue = (value: string) => {
      return value.trim()
    }
    const registerFormRules = reactive<FormRules>({
      email: [{ trigger: 'blur', validator: validateEmail }],
      name: [
        { required: true, message: '请输入昵称', trigger: 'blur', transform: transformValue },
        { max: 8, message: '昵称不能超过8个字符', trigger: 'blur', transform: transformValue },
      ],
      password: [{ trigger: 'blur', validator: validPassword }],
      confirmPassword: [{ trigger: 'blur', validator: validConfirmPwd }],
    })
    const router = useRouter()
    // 跳转登录
    const toLogin = () => {
      router.push('/signIn/login')
    }
    const formRef = ref<FormInstance | null>()
    const registerAccount = () => {
      if (!formRef) return
      formRef.value?.validate(async (valid) => {
        if (valid) {
          loading.value = true
          const res = await createUser({
            email: registerForm.email,
            nickName: registerForm.name,
            password: registerForm.password,
          })
          loading.value = false
          if (res && res.code === 0) {
            ElMessage.success({
              duration: 1000,
              message: '注册成功,正在跳转登录页...',
            })
            setTimeout(() => {
              router.push('/signIn/login')
            }, 1000)
          }
        }
      })
    }
    return {
      registerForm,
      registerFormRules,
      formRef,
      loading,
      toLogin,
      registerAccount,
    }
  },
})
</script>

<style lang="scss" scoped>
.register-form {
  width: 400px;
  background-color: #fff;
  margin: 0 auto;
  .register-btn {
    color: var(--text-primary);
    &:hover {
      color: #76839b;
      text-decoration: underline;
    }
  }
}
</style>
